package com.pinyoumei.app.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.AccountBean;
import com.pinyoumei.app.bean.RegisterBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.LogUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.SwipeMenuLayout;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.reactivestreams.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.realm.Realm;
import io.realm.RealmResults;


/**
 * 切换账号
 */
public class SwitchAccountActivity extends AppCompatActivity implements View.OnClickListener{
    private int position_select = 0;//记录选择了那个地址 默认是第一个选择
    private RelativeLayout relative_finish;
    private RelativeLayout relative_addmore;//添加账号
    private RecyclerView recyclerview;
    private List<AccountBean> list = new ArrayList<>();
    private RecyclerViewAdapter recyclerViewAdapter;
    private LoadingDailog loadingDailog;
    private Subscriber subscriber;
    protected AppManager appManager = AppManager.getInstance();
    private Gson gson;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtils.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明
        StatusBarUtils.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtils.setStatusBarDarkTheme(this, true)){
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtils.setStatusBarColor(this,0x55000000);
        }

        setContentView(R.layout.activity_layout_switchaccount);
        initwidget();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        gson = new Gson();
        //从本地数据库拿取保存账号信息
        //查询数据库
        Realm realm = Realm.getDefaultInstance();
        RealmResults<AccountBean> accountBeans = realm.where(AccountBean.class).findAllAsync();
        list.addAll(realm.copyFromRealm(accountBeans));
       LogUtils.e("Log","list = "+list.size());
        recyclerViewAdapter = new RecyclerViewAdapter(list,this);
        recyclerview.setAdapter(recyclerViewAdapter);
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
             case R.id.relative_finish:
                 finish();
                 break;
            case R.id.relative_addmore://添加账号
                startActivity(new Intent(this,AddAccountActivity.class));
                break;
        }
    }

    @Override
    protected void onResume(){
        super.onResume();
        //从本地数据库拿取保存账号信息
        //查询数据库
        Realm realm = Realm.getDefaultInstance();
        RealmResults<AccountBean> accountBeans = realm.where(AccountBean.class).findAllAsync();
        list.clear();
        list.addAll(realm.copyFromRealm(accountBeans));
        recyclerViewAdapter.notifyDataSetChanged();
    }
    private void initwidget(){
        relative_finish = findViewById(R.id.relative_finish);
        relative_finish.setOnClickListener(this);
        relative_addmore = findViewById(R.id.relative_addmore);
        relative_addmore.setOnClickListener(this);
        recyclerview = findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(linearLayoutManager);
    }
    class RecyclerViewAdapter extends RecyclerView.Adapter{
        private List<AccountBean> list;
        private Context context;
        public RecyclerViewAdapter(List<AccountBean> list,Context context){
            this.context = context;
            this.list = list;
        }
        @Override
        public int getItemViewType(int position){
            return position;
        }
        @Override
        public int getItemCount(){
            return list.size();
        }
        @Override
        public long getItemId(int position){
            return position;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i){
            View view = LayoutInflater.from(context).inflate(R.layout.item_layout_account,viewGroup,false);
            return new MyViewHolder(view);
        }
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, @SuppressLint("RecyclerView") final int position){
            if(SPUtils.getAppUserId(context).equals(list.get(position).getApp_user_id())){//如果当前登录用户的appuserid跟列表里面的id一致则红沟定位在该item上
                ((MyViewHolder)viewHolder).image_select.setVisibility(View.VISIBLE);
            }else{
                ((MyViewHolder)viewHolder).image_select.setVisibility(View.GONE);
            }
            ((MyViewHolder)viewHolder).relative_click.setOnClickListener(new View.OnClickListener(){//条目点击 每次点击就是登陆
                @Override
                public void onClick(View v){
                    position_select = position;
                    notifyDataSetChanged();
                    LoginData(list.get(position).getPhone(),list.get(position).getPassword(), 1);
//                    login(list.get(position).getPhone(),list.get(position).getPassword(), Constants.OEM_ID,"1");//安卓设备的登录
                }
            });
            ((MyViewHolder)viewHolder).text_name.setText(list.get(position).getName());
            ((MyViewHolder)viewHolder).text_phone.setText(list.get(position).getPhone());

            ((MyViewHolder)viewHolder).swipeMenuLayout.setIos(false);//设置是否开启IOS阻塞式交互
            ((MyViewHolder)viewHolder).swipeMenuLayout.setLeftSwipe(true);//true往左滑动,false为往右侧滑动
            ((MyViewHolder)viewHolder).swipeMenuLayout.setSwipeEnable(true);//设置侧滑功能开关
            //点击删除按钮
            ((MyViewHolder)viewHolder).relative_delete.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    String phone = list.get(position).getPhone();//用户手机号是主键 删除该用户
                    //查询数据库
                    Realm realm = Realm.getDefaultInstance();
                    RealmResults<AccountBean> accountBeans = realm.where(AccountBean.class).findAll();
                    realm.executeTransaction(new Realm.Transaction(){
                        @Override
                        public void execute(Realm realm){
                            if(accountBeans.size()>0){
                                accountBeans.deleteFromRealm(position);
                                list.remove(position);
                                notifyDataSetChanged();
                            }
                        }
                    });
                    if(SPUtils.getUserLoginInfor(context).getString("username","").equals(phone)){//如果当前登录用户被删除 则提示不能删除正在登录的账户
                       //删除登录用户的话 需要退出登录然后进入登录界面
                        SPUtils.clearAppUserid(SwitchAccountActivity.this);//清除用户id
                        SPUtils.clearUserLoginInfor(SwitchAccountActivity.this);//清除用户登录信息
//                        JPushInterface.deleteAlias(SwitchAccountActivity.this,200);
                        startActivity(new Intent(SwitchAccountActivity.this,LoginActivity.class));//进入登录界面
                        AppManager.getInstance().AppExit(SwitchAccountActivity.this);//销毁所有的Activity
                    }
                }
            });
        }
        class MyViewHolder extends RecyclerView.ViewHolder{
            private TextView text_name;
            private TextView text_phone;
            private ImageView image_user_icon;
            private ImageView image_select;
            private RelativeLayout relative_click;
            private SwipeMenuLayout swipeMenuLayout;
            private RelativeLayout relative_delete;
            public MyViewHolder(View view){
                super(view);
                image_user_icon = view.findViewById(R.id.image_user_icon);
                image_select = view.findViewById(R.id.image_select);
                relative_click = view.findViewById(R.id.relative_click);
                text_name = view.findViewById(R.id.text_name);
                text_phone = view.findViewById(R.id.text_phone);
                swipeMenuLayout = view.findViewById(R.id.swipeMenuLayout);
                relative_delete = view.findViewById(R.id.relative_delete);
            }
        }
    }
    //添加账号登录请求
//    private void login(String user_phone,String user_pwd,String oem_id,String app_type){
//        Map<String,Object> map = new HashMap<>();
//        map.put("user_phone",user_phone);
//        map.put("user_pwd",user_pwd);
//        map.put("oem_id",oem_id);
//        map.put("app_type",app_type);//app类型 1:安卓 2ios
//        map.put("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET));
//        subscriber = new Subscriber<LoginResponse>() {
//            @Override
//            public void onStart() {
//                super.onStart();
//                loadingDailog.show();
//            }
//            @Override
//            public void onCompleted(){
//
//            }
//            @Override
//            public void onError(Throwable e){
//                loadingDailog.dismiss();
//            }
//
//            @Override
//            public void onNext(LoginResponse loginResponse){
//                loadingDailog.dismiss();
//                if(loginResponse.getCode() >= 0){//登录成功保存用户id
//
//
//                    PushData(SPUtils.getAppUserId(SwitchAccountActivity.this),"");
//                    PushData(loginResponse.getResult().getUser_id(),SPUtils.getChannelId(SwitchAccountActivity.this));
//                    //保存用户id 本地保存跟静态变量保存
//                    SPUtils.saveAppUserId(SwitchAccountActivity.this,loginResponse.getResult().getUser_id());
//                    //保存用户的登录信息 用户名 密码
//                    SPUtils.saveUserLoginInfor(SwitchAccountActivity.this,user_phone,user_pwd);
//
//
//
//
//
//
//                    ClearCahceUtils.clearAllCache(SwitchAccountActivity.this);
//                    CacheManager.getInstance().clear();
//                    EventBusUtils.postSticky(new MineFragmentEvent("mine_fresh"));
//                    EventBusUtils.postSticky(new HomeFragmentEvent("home_fresh"));
//                    EventBusUtils.postSticky(new VideoFragmentEvent("video_fresh"));
//                    EventBusUtils.postSticky(new AchiveFragmentEvent("achive_fresh"));
//                    EventBusUtils.postSticky(new SuperVipFragmentEvent("vip_fresh"));
//                    EventBusUtils.post(new PointSecondSelectEvent(0));
//
//
//                    //在切换账号的时候需要返回到主界面
//                    AppManager.getInstance().killActivity(SettingCenterActivity.class);
//                    AppManager.getInstance().killActivity(UserSettingActivity.class);
//                    finish();
//                }else{
//                    ToastUtils.showShort(loginResponse.getMsg());
//                }
//            }
//        };
//        HttpMethods.getInstance().login(subscriber,map);
//    }


    //物理返回键的监听

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//            startActivity(new Intent(this,SettingCenterActivity.class));
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
private void PushData( String user_id,String channel_id) {

    Map<String,Object> map = new HashMap<>();
    map.put("user_id",user_id);
    map.put("channel_id", channel_id);


    OkGo.<String>post( Constants.PUSH_BAIDU)
            .params("user_id",user_id)
            .params("channel_id",channel_id)
            .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
            .execute(new StringCallback() {




                @Override
                public void onStart(Request<String, ? extends Request> request) {
                    super.onStart(request);

                }

                @Override
                public void onSuccess(Response<String> response) {


//                        BaseBean financingBean = gson.fromJson(response.body(), BaseBean.class);
//                        if (financingBean.getCode() >= 0 ){
//
//
//                        }else{
//                            ToastUtils.showShort(financingBean.getMsg());
//                        }

                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);

                }
            });





}


    private void LoginData(String user_phone,String user_pwd,int app_type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", user_phone);
        map.put("user_pwd", user_pwd);
        map.put("app_type", app_type);

        OkGo.<String>post(Constants.LOGIN_CHECK)
                .params("user_phone", user_phone)
                .params("user_pwd", user_pwd)
                .params("app_type", app_type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        RegisterBean registerBean = gson.fromJson(response.body(), RegisterBean.class);

                        if (registerBean.getCode() >= 0) {

                            //保存登录账号的信息的实体类到本地数据库
                            Realm realm = Realm.getDefaultInstance();
                            AccountBean accountBean = new AccountBean();
                            accountBean.setName(registerBean.getResult().getUser_name());
                            accountBean.setPhone(registerBean.getResult().getUser_phone());
                            accountBean.setPassword(user_pwd);
                            accountBean.setApp_user_id(registerBean.getResult().getUser_id());
                            accountBean.setUser_head_image(registerBean.getResult().getUser_head_img());
                            realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {
                                    realm.copyToRealmOrUpdate(accountBean);
                                    //进入主界面
                                    SPUtils.saveAppUserId(SwitchAccountActivity.this,registerBean.getResult().getUser_id());

                                    SPUtils.saveUserPhone(SwitchAccountActivity.this,registerBean.getResult().getUser_phone());


                                    appManager.killActivity(LoginActivity.class);
                                    startActivity(new Intent(SwitchAccountActivity.this,MainUIActivity.class));
                                    finish();
                                }
                            });



                        } else {
                            Toast.makeText(SwitchAccountActivity.this, registerBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }
    
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (subscriber!=null && !subscriber.isUnsubscribed()) {
//            subscriber.unsubscribe();
//        }
    }


}
